﻿using AddressBooks.Entities;
using AddressBooks.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Data;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace AddressBooks.ViewModel;


public partial class ContactsViewModel : BasePageViewModel<Contacts>, ICrumbsBar
{
    readonly ContactsManager service = new();
    readonly OrgManager orgService = new();

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Pager))]
    private List<ShowContact> items;
    [ObservableProperty]
    private List<Org> rootListTreeData;
    [ObservableProperty]
    private Org selectedRootNode;
    [ObservableProperty]
    private Org selectedFirstLevelNode;
    [ObservableProperty]
    private Org selectedSencondLevelNode;
    [ObservableProperty]
    private List<Org> selectedItems;

    [RelayCommand]
    private async Task FirstLevelNodeSelectedAsync(Org o)
    {
        if (o == null)
        {
            return;
        }
        Growl.Info("选择" + o.Name);
        Initialize();
        Parameters = Expressionable.Create<Contacts>();
        // exp.OrIF(条件, it => it.Id == 1);//.OrIf 是条件成立才会拼接OR
        // exp.Or(it => it.Name.Contains("jack"));//拼接OR
        Parameters.And(it => it.Orgid == o.Id);
        OrderBys = new() { "`order`" };
        await GetData();
    }
    /// <summary>
    /// 初始化命令
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    [RelayCommand]
    private void Initialized()
    {
        Pager = new() { CurrentPageIndex = 1, Limit = 10, TotalPages = 1 };
        _ = GetData();
    }

    private void Initialize()
    {
        Pager.CurrentPageIndex = 1;
        Pager.TotalPages = 1;
    }

    // <summary>
    // 触发批量删除命令
    // </summary>
    // <returns></returns>
    [RelayCommand]
    private async Task BatchDelete()
    {
        Items.ForEach(o =>
        {
            Debug.WriteLine(o.Name);
        });
        Initialize();
        //await GetData();
    }
    /// <summary>
    /// 触发查询处理命令
    /// </summary>
    /// <returns></returns>
    //[RelayCommand]
    //private async Task SearchTitle()
    //{
    //    Initialize();
    //    pars.Parameters?.Add(new QueryParameter() { ConditionalType = ConditionalType.Like, FieldName = "title", FieldValue = $"_%{Stitle}%" });
    //    pars.OrderBys = (new() { "orgid", "`order`" }); 
    //    await GetData();
    //}
    /// <summary>
    /// 触发查询处理命令
    /// </summary>
    /// <returns></returns>
    //[RelayCommand]
    //private async Task SearchNumber()
    //{
    //    Initialize();
    //    pars.Parameters?.Add(new QueryParameter() { ConditionalType = ConditionalType.Like, FieldName = "cell", FieldValue = $"_%{Snum}%" });
    //    pars.OrderBys = (new() { "orgid", "`order`" }); 
    //    await GetData();
    //}

    /// <summary>
    /// 根据分页和查询条件查询，请求数据
    /// </summary>
    /// <returns></returns>
    public async Task GetData()
    {
        var res = await service.GetContactsPageListAsync(Parameters, OrderBys, Pager);
        if (res != null)
        {

            Items = res.Select(it => new ShowContact(it))
                       .ToList();
        }
        else Items = new();
    }

    /// <summary>
    /// 触发的分页处理命令
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    [RelayCommand]
    private async Task PageUpdated(FunctionEventArgs<int> info)
    {
        //根据分页页码展示
        Pager.CurrentPageIndex = info.Info;

        //查询更新
        await GetData();
    }

    #region 地址栏处理函数

    /// <summary>
    /// 触发面包屑查询处理命令
    /// </summary>
    [RelayCommand]
    public async Task CrumbsBarSearchAsync(string key)
    {
        if (key == "") return;
        Parameters = Expressionable.Create<Contacts>();
        // exp.OrIF(条件, it => it.Id == 1);//.OrIf 是条件成立才会拼接OR
        // exp.Or(it => it.Name.Contains("jack"));//拼接OR
        if (int.TryParse(key, out int i))
        {
            Parameters.Or(it => it.Cell.Contains(key) || it.Other.Contains(key) || it.Work.Contains(key));
        }
        else
        {
            Parameters.Or(it => it.Name.Contains(key) || it.Org.Contains(key) || it.Title.Contains(key));
        }

        OrderBys = new()
        {
            //"uptime desc",
            "orgid",
            "`order`"
        };
        try
        {
            Initialize();
            //查询更新
            await GetData();
        }
        catch (Exception)
        {
            Growl.Error("查询出错");
        };
    }

    [RelayCommand]
    public void CrumbsBarLeftButtonClick()
    {
        throw new NotImplementedException();
    }

    [RelayCommand]
    public void CrumbsBarRightButtonClick()
    {
        throw new NotImplementedException();
    }

    [RelayCommand]
    public void CrumbsBarDownButtonClick()
    {
        throw new NotImplementedException();
    }

    [RelayCommand]
    public Task CrumbsBarRefreshButtonClick()
    {
        throw new NotImplementedException();
    }
    #endregion
    public Expressionable<Contacts> Parameters { get; set; }
    public List<string> OrderBys { get; set; }
    public ContactsViewModel()
    {

        pager = new() { CurrentPageIndex = 1, Limit = 10, TotalPages = 1 };
        rootListTreeData = orgService.GetTree();
    }

}
